﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using StartStop.ServiceResources;

namespace StartStop.Helpers
{
    public class UserPreferences
    {
        public const string LiveConnectionString =
            "data source=v2.startstop.me;initial catalog=startstop;persist security info=True;user id=sa;password=PASSWORD;";

        public static MessageResponse SaveUserSetting(Setting InboundSetting)
        {
            // Use the SQL within this 
            var conn = new SqlConnection(LiveConnectionString);
            conn.Open();
            var sCom = new SqlCommand();
            sCom.Connection = conn;
            
            var oResponse = new MessageResponse();
            // First of all look to see if the setting exists
            string settingID =
                Sql.ExecuteScalar("Select * from UsersExtendedPreferences where UserID = " +
                                  InboundSetting.UserID.ToString() + " and PrefName = '" + InboundSetting.PreferenceName +
                                  "'");
            if (settingID != "")
            {
                sCom.CommandText =
                    @" 
                        Update UsersExtendedPreferences 
                        set
                        PrefSettingBool = @prefsbool,
                        PrefType = @prefType, 
                        PrefSettingInt = @prefsInt, 
                        PrefSettingText = @prefsText, 
                        ModifiedOn = getDate()
                        where EUserPrefsID = @settingID
                        ";
            }
            else
            {
                sCom.CommandText =
                    @" 
                        Insert into UsersExtendedPreferences (PrefSettingBool,PrefSettingInt,PrefSettingText, UserID, PrefName, CreatedOn, PrefType)
                        values (@prefsbool, @prefsInt,@prefsText, @UserId, @PRefName, GetDate(), @PrefType);";
            }

            sCom.Parameters.AddWithValue("@prefsbool", InboundSetting.PreferenceBool);
            sCom.Parameters.AddWithValue("@prefsInt", InboundSetting.PreferenceInt);
            if (InboundSetting.PreferenceString == null)
            {

                sCom.Parameters.AddWithValue("@prefstext", DBNull.Value);
            }
            else
            {
                sCom.Parameters.AddWithValue("@prefstext", InboundSetting.PreferenceString);
            }
            sCom.Parameters.AddWithValue("@settingID", settingID);
            sCom.Parameters.AddWithValue("@UserID", InboundSetting.UserID);
            sCom.Parameters.AddWithValue("@PrefName", InboundSetting.PreferenceName);
            sCom.Parameters.AddWithValue("@PrefType", InboundSetting.PreferenceType);
            sCom.ExecuteScalar();

            conn.Close();
            return oResponse;
        }

        // Returns a list of all the users settings. 
        public static UserSettings ReturnUserSettings(Int64 userID)
        {
            DataTable oAllSettings =
                Sql.ReturnDataTable("select * from UsersExtendedPreferences where UserID = " + userID);
            var oSettings = new UserSettings();
            oSettings.Settings = new List<Setting>();
            oSettings.UserID = userID;
            foreach (DataRow oRow in oAllSettings.Rows)
            {
                var oSetting = new Setting();

                oSetting.SettingID = Int64.Parse(oRow["EUserPrefsID"].ToString());

                if (oRow["CreatedOn"].ToString() != "")
                {
                    oSetting.CreatedOn = DateTime.Parse(oRow["CreatedOn"].ToString());
                }
                if (oRow["ModifiedOn"].ToString() != "")
                {
                    oSetting.ModifiedOn = DateTime.Parse(oRow["ModifiedOn"].ToString());
                }
                oSetting.PreferenceBool = (bool)oRow["PrefSettingBool"];
                if (oRow["PrefSettingInt"].ToString() != "")
                {
                    oSetting.PreferenceInt = (int)oRow["PrefSettingInt"];
                }

                oSetting.PreferenceName = (string)oRow["PrefName"];
                if (oRow["PrefSettingText"] != null)
                {
                    oSetting.PreferenceString = oRow["PrefSettingText"].ToString();
                }

                if (oSetting.PreferenceType.ToString() != "")
                {
                    oSetting.PreferenceType = int.Parse(oRow["PrefType"].ToString());
                }
                oSettings.Settings.Add(oSetting);

            }

            return oSettings;
        }

        // Returns a single setting
        public static Setting ReturnSingleSetting(Int64 userID, string PreferenceName)
        {

            DataTable oAllSettings =
                Sql.ReturnDataTable("select * from UsersExtendedPreferences where UserID = " + userID + " and PrefName= '" + PreferenceName + "'");
            Setting oSetting = null;
            foreach (DataRow oRow in oAllSettings.Rows)
            {
                oSetting = new Setting(); 
                oSetting.SettingID = Int64.Parse(oRow["EUserPrefsID"].ToString());

                if (oRow["CreatedOn"].ToString() != "")
                {
                    oSetting.CreatedOn = DateTime.Parse(oRow["CreatedOn"].ToString());
                }
                if (oRow["ModifiedOn"].ToString() != "")
                {
                    oSetting.ModifiedOn = DateTime.Parse(oRow["ModifiedOn"].ToString());
                }
                oSetting.PreferenceBool = (bool)oRow["PrefSettingBool"];
                if (oRow["PrefSettingInt"].ToString() != "")
                {
                    oSetting.PreferenceInt = (int)oRow["PrefSettingInt"];
                }

                oSetting.PreferenceName = (string)oRow["PrefName"];
                if (oRow["PrefSettingText"] != null)
                {
                    oSetting.PreferenceString = oRow["PrefSettingText"].ToString();
                }

                if (oSetting.PreferenceType.ToString() != "")
                {
                    oSetting.PreferenceType = int.Parse(oRow["PrefType"].ToString());
                }
            }
            return oSetting;
        }

        /// <summary>
        /// This just creates default rows in the extend preferences so that none are missing when the user tries to make changes
        /// This will also make it easier to deal with adding new ones. 
        /// I was thinking of making the default settings to be part of the system settings. 
        /// </summary>
        /// <param name="userID"></param>
        public static bool CheckDefaultUserSettings(Int64 userID)
        {



            List<StartStop.DataSetup.DefaultUserExtendedPreferences> oList = StartStop.DataSetup.ReturnDefaults.ReturnExtendedPrefs();
            foreach (var item in oList)
            {


                string _response = StartStop.Helpers.Sql.ExecuteScalar("Select * from UsersExtendedPreferences where UserID = " + userID.ToString() + " and PrefName = '" + item.Name + "'");
                if (_response == "")
                {
                    // We need to generate the default setting here
                    Setting oNewSetting = new Setting();
                    oNewSetting.PreferenceName = item.Name;
                    oNewSetting.PreferenceType = item.PreferenceType;
                    oNewSetting.UserID = userID;

                    /// This is going to need extending for all the different preference types. 
                    if (item.PreferenceType == 2)
                    {
                        oNewSetting.PreferenceBool = bool.Parse(item.DefaultSetting);
                    }

                    SaveUserSetting(oNewSetting);

                }
            }

            return true;
        }

    }
}